package codeRandomThoughts.Test113路径总和II;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>>  pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root==null){
            return res;
        }
        List<Integer> path = new ArrayList<>();
        backTrack(root, path, targetSum, res);
        return res;
    }

    void backTrack(TreeNode root, List<Integer> path, int targetSum, List<List<Integer>> res) {
        path.add(root.val);
        //结束条件为遍历到叶子结点
        if (root.left == null && root.right == null) {
            //检测路径和是否与目标相等
            if (listSum(path) == targetSum) {
                res.add(new ArrayList<>(path));
            }
        }

        if (root.left != null) {
            backTrack(root.left, path, targetSum, res);
            path.remove(path.size() - 1);//回溯
        }
        if (root.right != null) {
            backTrack(root.right, path, targetSum, res);
            path.remove(path.size() - 1);//回溯
        }
    }

    int listSum(List<Integer> path) {
        int sum = 0;
        for (int i = 0; i < path.size(); i++) {
            sum += path.get(i);
        }
        return sum;
    }

}
